import React,{FC} from 'react';
import {Form,Input,Select,Button,message} from 'antd';
import style from './consumer.less';
import {useSelector,ConsumerModelState,useDispatch} from 'umi';

const { Option } = Select;

interface Iprops{
    item:any
}

const Consumer:FC<Iprops> = ({item}) => {

    const [form] = Form.useForm();

    const dispatch = useDispatch();

    const top = item.top;
    const con = item.con;
    const submitType = item.submitType;

    //仓库的数据拿出来 

    const consumerStore = useSelector((model:{consumer:ConsumerModelState}) => model.consumer);

    console.log("consumerStore",consumerStore)

    //consumerStore[item.showData]

    const onFinish =  (values: any) => {
        console.log(values,"values=============================");
        //调添加的接口  addUser
        let result:any = dispatch({
            type:'consumer/submitApi' ,
            payload:{
                type:submitType,
                data:values
            }
        })

        result.then((res:{code:number,msg:string,user_id:string}) => {
            if(res.code === 1){
                message.success(res.msg)
            }else{
                message.error(res.msg)
            }
            //重置表单的内容
            form.resetFields();
        })

    };

    //重置表单内容
    const onReset = () => {
        form.resetFields();
    }

    return <div className={style.consumerWrap}>
            <div>
                {top.map((val:{id:string,text:string}) => <Button key={val.id}>{val.text}</Button>)}
            </div>
            <Form 
                form={form} 
                onFinish={onFinish}
            >
                {con.map((val:any) => {
                    if(val.type === 'input') {
                        return <Form.Item name={val.field} rules={val.rules} key={val.id}>
                            <Input placeholder={val.placeholder}/>
                        </Form.Item>
                    }else if(val.type === 'select'){
                        return <Form.Item name={val.field} rules={val.rules}  key={val.id}>
                            <Select placeholder={val.placeholder}
                            >
                                {(consumerStore as {[propName:string]:any})[val.showData].map((v:any) => <Option key={v[val.value]} value={v[val.value]}>{v[val.text]}==={v[val.value]}</Option>)}
                            </Select>
                        </Form.Item>
                    }
                })}
            <Form.Item> 
                <Button type="primary" htmlType="submit">
                    提交
                </Button>
                <Button htmlType="button" onClick={onReset}>
                    重置
                </Button>
            </Form.Item>
        </Form>
    </div>
        
}

export default Consumer